$(function () {
    getSysUserList(1);
    $("body").on('click', '#btn1,#btn2', function () {
        //点击搜索查询从第一页开始查询
        getSysUserList(1);
    }).on('click', 'i.fa-unlock-alt', function () { //单个禁用
        var id = $(this).parent().data('id');
        icModale(2, '确认禁用选中的系统帐号', 3, function () {
            updateSysUserStatus(id,2);
        });
    }).on('click', 'i.fa-check', function () { //单个通过申请
        var id = $(this).parent().data("id");
        icModale(2, '确认通过体验帐号的申请', 3, function () {
            updateSysUserStatus(id,1);
        });
    }).on('click', 'i.fa-history', function () { //单个恢复
        var id = $(this).parent().data("id");
        icModale(2, '确认恢复禁用的系统帐号', 3, function () {
            updateSysUserStatus(id,1);
        });
    }).on('click', '#ban-sysUser', function () { //批量禁用
        var ids = getSelectId();//获取选中的ID
        if(ids==null){
            icModale(0, '请选择要禁用的用户');
            return;
        }
        icModale(2, '确认禁用选中的系统帐号', 3, function () {
            updateSysUserStatus(ids, 2);
        });
    }).on('click', '#approve-sysUser', function () { //批量通过申请
        var ids = getSelectId();//获取选中的ID
        if(ids==null){
            icModale(0, '请选择要通过申请的用户');
            return;
        }
        icModale(2, '确认通过选中的系统帐号的申请', 3, function () {
            updateSysUserStatus(ids,1);
        });
    }).on('click', '#recover-sysUser', function () { //批量恢复
        var ids = getSelectId();//获取选中的ID
        if(ids==null){
            icModale(0, '请选择要恢复的用户');
            return;
        }
        icModale(2, '确认恢复选中的系统帐号', 3, function () {
            updateSysUserStatus(ids,1);
        });
    }).on('click', '#group', function () { //选择部门
        getGroupWin();
    }).on('click', '#clearGroup', function () { //清空部门
        $('#hiddenGroupId').val('');
        $('#group').val('');
        $('#clearGroup').blur();
    }).on('click', 'i.fa-eye', function () { //查看系统用户
        var id = $(this).parent().data('id');
        parent.layer.open({
            type: 2,
            area: ['900px', '520px'],
            content: baseloaction + '/admin/manage/user/showUserInfo?userId=' + id,
            maxmin: true,
            shade: [0.3, '#000'],
            shadeClose: false,
            title: '<strong>查看账号</strong>',
            btn:["进入修改状态","取消"],
            yes: function (index, layero) {
                window.location.href = baseloaction + '/admin/manage/user/initUpdate?userId=' + id;
                parent.layer.close(index);
            }
        });
    }).on('click','i.fa-clock-o',function () {//申请延期
        var id = $(this).parent().data("id");
        var _this = $(this);
        icModale(2, '确认延期选中的系统帐号',3, function () {
           $.ajax({
               url: baseloaction + "/admin/manage/user/delayedUser",
               data: {"userIds": id},
               type: "post",
               dataType: "json",
               success: function (result) {
                   icModale(0, result.message);
                   if(result.success){
                       var endTime = result.entity.substring(0,10);
                       if(endTime!=null && $.trim(endTime)!=''){
                           $("#end-time-"+id).text(endTime);
                           _this.parent('a').remove();
                       }
                   }
               },
               error: function (error) {
                    icModale(0, "系统繁忙，请稍后重试");
               }
           });
        });
    }).on('click',"i.fa-key",function () {//修改密码
        var userId = $(this).parent().data("id");
        var context = '<div class="m-t m-r m-l m-b">' +
            '请输入新密码：<input class="form-control" id="newPassword" type="password">' +
            '</div>';
        parent.layer.open({
            type: 1,
            area: ['380px'],
            skin: 'layui-layer-demo',
            title: '修改密码',
            content:context ,
            btn: '确定',
            yes: function (index, layero) {
                var newPassword = layero.find('#newPassword').val();
                $.ajax({
                    url: baseloaction +'/admin/manage/user/updateUserPwd',
                    type:'post',
                    dataType:'json',
                    data:{'newPassword':newPassword,'userId':userId},
                    success:function (result) {
                        icModale(0,result.message);
                        if(result.success==true){
                            parent.layer.close(index);
                        }
                    },
                    error:function (error) {
                        icModale(0,"系统错误，修改密码失败");
                    }
                });
            }
        });
    }).on('click','#individual-authorization',function () {//单独授权
        var userId = $(this).data('id');
        parent.layer.open({
            type: 2,
            area: winArea,
            content: baseloaction + '/admin/manage/user/initUserAuthorization?userId=' + userId,
            maxmin: true,
            shade: [0.3, '#000'],
            shadeClose: false,
            title: '<strong>单独授权用户</strong>',
            btn: ['确认授权','取消'],
            yes: function (index,layero) {
                var _iframe = layero.find("iframe:visible");
                var iframeName = _iframe[0].name;
                var functionIds = parent.frames[iframeName].getFunctionData();
                $.ajax({
                    url:baseloaction +'/admin/manage/user/saveUserFunction',
                    type:'post',
                    dataType:'json',
                    data:{
                        'functionIds':functionIds,
                        'userId':userId
                    },
                    success:function(result){
                        if(result.success==true){
                            parent.layer.close(index);
                        }else{
                            icModale(0,result.message);
                        }
                    },
                    error:function(error){
                        icModale(0,'系统错误，用户授权失败');
                    }
                });
            },
            btn2: function(index) {
                parent.layer.close(index);
            }
        });
    });

    /**
     * 获取选中的ID串
     * @return {null}
     */
    function getSelectId() {
        var selected = $('td input.i-checks:checked');
        if(selected!=null && selected.length>0){
            var ids = selected.map(function () {
                return this.value;
            }).get().join(',');
            return ids;
        }
        return null;
    }
    /**
     * 更新系统用户状态
     * @param userIds 用户ID串
     * @param status 状态，1正常，2禁用，3删除
     */
    function updateSysUserStatus(userIds,status) {
        $.ajax({
            url: baseloaction + '/admin/manage/user/updateSysUserStatus',
            data: {'userIds': userIds, 'status': status},
            dataType: 'json',
            success: function (response) {
                icModale(0, response.message);
                if (response.success) {//如果操作成功
                    var arr = (userIds+"").split(",");
                    $.each(arr,function () {
                        if(this!=null && $.trim(this)!=''){
                            var actionEm = $("#status-action-"+this);
                            if (status == 3){//删除用户
                                $("#sys-user-"+this).remove();
                            }else if(status==2){//禁用
                                actionEm.attr('data-original-title','恢复');
                                actionEm.html('<i class="fa fa-history"></i>');
                                $("#status-"+this).html('<span class="label label-danger">禁用</span>');
                                //$("#approve-"+this).html('—');
                            }else if(status==1){//恢复
                                actionEm.attr('data-original-title','禁用');
                                actionEm.html('<i class="fa fa-unlock-alt"></i>');
                                $("#status-"+this).html('<span class="label label-info">正常</span>');
                                var userType = actionEm.data('user-type');
                                userType = parseInt(userType);
                                if(userType==2){
                                    $("#approve-"+this).html('<span class="label label-info">已批准</span>');
                                }
                            }
                        }
                    });
                }
            }
        });
    }
    /**
     * 获取用户列表页面
     * @param pageNo 当前页码
     */
    function getSysUserList(pageNo) {
        var params = $("#search-form").serializeJSON();
        params = JSON.stringify(params);
        var obj = {
            url: baseloaction + '/admin/manage/user/ajaxQueryUserList',//请求URL
            contextId: 'oc-ibox-content',//响应内容页面设置内容ID
            params: params,//请求参数
            pageNo: pageNo,//页码
            pageCall: getSysUserList, //分页回调加载数据(点击上下页时调用,该方法也在加载页面完成时调用)
            selectAllId: 'all-sysUser', //全选框ID
            callback: function () {//数据加载完成回调

            }
        };
        ajaxGetListData(obj);
    }
});

/**
 * 选择部门回调
 * @param obj 选择部门的数据
 */
function groupCallback(obj) {
    $("#hiddenGroupId").val(obj.groupId);
    $("#group").val(obj.groupName);
}